package com.example.demo.controller;

import com.example.demo.controller.common.ResultVO;
import com.example.demo.controller.vo.LikeVO;
import jakarta.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping
public class LikeController {
    @Resource
    private JdbcTemplate jdbcTemplate;
    /**
     *
     * @param vo
     * @return
     */
    @PutMapping("/like")
    public ResultVO<Map> like(@RequestBody LikeVO vo) {
        String selectSql = "select t.user_id,t.content_id,t.like_time from user_content_like t where t.user_id = ? and t.content_id = ?";
        List<Map<String, Object>> checkList = jdbcTemplate.queryForList(selectSql, vo.getUserId(), vo.getContentId());
        if (checkList != null && checkList.size() > 0) {
            return ResultVO.success(checkList.get(0));
        }
        String sql = "INSERT INTO `study`.`user_content_like`(`user_id`, `content_id`, `like_time`) " +
                "VALUES (?, ?, now())";
        int update = jdbcTemplate.update(sql, vo.getUserId(), vo.getContentId());
        if (update <= 0) {
            return ResultVO.fail(500, "点赞失败");
        }
        List<Map<String, Object>> likeList = jdbcTemplate.queryForList(selectSql, vo.getUserId(), vo.getContentId());
        if (likeList == null || likeList.size() <= 0) {
            return ResultVO.fail(500, "点赞失败");
        }
        return ResultVO.success(likeList.get(0));
    }
    @DeleteMapping("/unlike")
    public ResultVO unLike(@RequestBody LikeVO vo) {
        String sql = "delete from user_content_like where user_id = ? and content_id = ? ";
        jdbcTemplate.update(sql, vo.getUserId(), vo.getContentId());
        return ResultVO.success();
    }

    @GetMapping("/like/query")
    public ResultVO query(LikeVO vo) {
        String selectSql = "select count(1) count_num from user_content_like t where  t.content_id = ?";
        Map<String, Object> map = jdbcTemplate.queryForMap(selectSql, vo.getContentId());
        return ResultVO.success(map);
    }
}
